import React from 'react';
import { Button, Col, Form, Input, message, Modal, Row, Select, Table, Pagination } from 'antd';
import styles from '@/pages/robotManagement/hotSpots/hotQuestion.css';
import { fetchHotTableData, fetchUserTypeList } from '@/services/hotQuestion';
import EditQuickModal from '@/pages/robotManagement/quickEntry/editQuickModal';
import { getQuickList, quickEntryMove, quickEntryRemove } from '@/services/quickEntry';

class QuickEntry extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      loading: false,
      total: 0,
      current: 1,
      size: 10,
      userList: [],
      entryName: '',
      userTypeId: ''
    }
  }

  componentDidMount() {
    this.getUserTypeList();
    this.getTableData();
  }

  /* 获取用户类型-筛选框 */
  getUserTypeList = async () => {
    const res = await fetchUserTypeList({ current: 1, size: 999999 });
    this.setState({
      userList: res.records ? res.records : [],
    })
  }

  /* 获取表格数据 */
  getTableData = () => {
    this.setState({ loading: true }, async () => {
      const { current, size, entryName, userTypeId } = this.state;
      const { applicationId } = this.props;
      const res = await getQuickList({ current, size, applicationId, entryName, userTypeId })
      this.setState({
        list: res.records ? res.records : [],
        total: res.total,
        loading: false
      })
    })
  }

  /* 分页 */
  changePagination = (current, size) => {
    this.setState({ current, size }, () => {
      this.getTableData();
    })
  }

  /* 打开编辑框 */
  openModal = (row) => {
    this.EditQuickModal.initOpen(row)
  }

  /* 条件查询 */
  searchByParams = () => {
    const info = this.props.form.getFieldsValue();
    this.setState({
      current: 1,
      userTypeId: info.userTypeId ? info.userTypeId : '',
      entryName: info.entryName ? info.entryName : ''
    }, () => {
      this.getTableData();
    })
  }

  /* 删除确认框 */
  deleteQuickConfirm = (id) => {
    const that = this;
    Modal.confirm({
      title: '确定要删除该快捷入口吗？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        that.removeEntry(id);
      },
    })
  }

  /* 删除-请求接口 */
  removeEntry = async id => {
    const res = await quickEntryRemove({ id })
    const { list, current } = this.state;
    if (list.length === 1 && current > 1) {
      this.setState({ current: current - 1, }, () => {
        this.getTableData();
      })
    } else {
      this.getTableData();
    };
    message.info(res.msg)
  }

  /** 上下移 */
  movePosition = async (row, index, flag) => {
    const { list } = this.state;
    const { applicationId } = this.props;
    let type = flag === 'up' ? 1 : 2
    const res = await quickEntryMove({ id: row.id, applicationId, type })
    message.info(res.msg);
    this.getTableData()
  }

  render() {
    const { list, loading, current, total, userList, size } = this.state;
    const { applicationId } = this.props;
    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: '入口名称',
        dataIndex: 'entryName',
        width: 150,
      },
      {
        title: '图片',
        dataIndex: 'imgUrl',
        width: 100,
        render: (imgSrc) => {
          if (imgSrc) {
            return <img src={imgSrc} style={{ width: 40, height: 40 }} />
          }
        }
      },
      {
        title: '链接地址',
        dataIndex: 'urlPath',
        width: 200,
      },
      {
        title: '适用用户类型',
        dataIndex: 'userTypeName',
        width: 350,
        render: (userTypeName) => {
          const list = userTypeName.split(',');
          return <div className={styles.userTypeBox}>
            {
              list.map((item, index) => {
                return <div key={index} className={styles.userTypeItem}>{item}</div>
              })
            }
          </div>
        }
      },
      {
        title: '操作',
        width: 250,
        render: (text, row, index) => {
          return (
            <div>
              <Button size='small' type='primary' icon='edit' style={{ marginRight: 4 }} onClick={() => this.openModal(row)}>
                编辑
              </Button>
              <Button size='small' type='primary' icon='delete' style={{ background: '#E8313B', borderColor: '#E8313B', marginRight: 4 }} onClick={() => this.deleteQuickConfirm(row.id)}>
                删除
              </Button>
              <Button
                style={{ marginRight: 4, background: current == 1 && index == 0 ? '#BFBFBF' : '#556FB5', color: "#ffffff" }}
                onClick={() => this.movePosition(row, index, 'up')}
                disabled={current == 1 && index == 0}
                icon="arrow-up"
                size="small"
              >
                上移
              </Button>
              <Button
                style={{ marginRight: 4, background: ((current - 1) * size + index + 1) == total ? '#BFBFBF' : '#8395FB', color: "#ffffff" }}
                onClick={() => this.movePosition(row, index, 'down')}
                disabled={((current - 1) * size + index + 1) == total}
                icon="arrow-down"
                size="small"
              >
                下移
              </Button>
            </div>
          );
        },
      },
    ];

    return (
      <div>
        <Row style={{ marginBottom: 20 }}>
          <Col span={20}>
            <Form layout="inline">
              <Form.Item label="入口名称">
                {getFieldDecorator('entryName')(<Input.Search placeholder="请输入" onSearch={this.searchByParams} />)}
              </Form.Item>
              <Form.Item label="用户类型">
                {getFieldDecorator('userTypeId', { initialValue: '' })(
                  <Select style={{ width: 200 }}>
                    <Select.Option value={''}>默认类型</Select.Option>
                    {
                      userList.map((item, index) => {
                        return <Select.Option value={item.id} key={item.id}>{item.tagName}</Select.Option>
                      })
                    }
                  </Select>
                )}
              </Form.Item>
              <Form.Item>
                <Button type='primary' onClick={this.searchByParams}>查询</Button>
              </Form.Item>
            </Form>
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            <Button type='primary' onClick={() => this.openModal()}>新增</Button>
            <div style={{ fontSize: '13px', color: "rgba(51, 51, 51, 0.5)", marginTop: 10 }}>此配置项对渠道原生页面无效。</div>
          </Col>
        </Row>

        <Table
          rowKey={'id'}
          columns={columns}
          dataSource={list}
          loading={loading}
          pagination={false}
          scroll={{ x: 'auto', y: 470 }}
        />
        {total > 10 ? (
          <Pagination
            style={{ textAlign: 'right', marginTop: 16 }}
            total={total}
            current={current}
            onChange={this.changePagination}
            // showSizeChanger={true}
            showQuickJumper={true}
            // onShowSizeChange={this.changePagination}
          />
        ) : null}

        <EditQuickModal
          onRef={ref => this.EditQuickModal = ref}
          applicationId={applicationId}
          userList={userList}
          refreshTableList={this.getTableData}
        />
      </div>
    );
  }
}

export default Form.create()(QuickEntry)
